package scuts.core;

import scuts.core.types.LazyIterator;


class FlattenArray {
  public static function flatten <T>(a:Array<Array<T>>):Array<T>
  {
    var res = [];
    for (a1 in a) {
      for (e in a1) {
        res.push(e);
      }
    }
    return res;
  }
}

class FlattenLazyIterator {
  public static function flatten < T > (v:LazyIterator<LazyIterator<T>>):LazyIterator<T> {
    
    return function () {
      
      var inInner = false;
      var outer = null;
      var inner:Iterator<T> = null;
      
      var res = {
        hasNext : null,
        next : function () return inner.next()
      }
      var outerF = null;
      var innerF = null;
      
      outerF = function () {
        if (outer == null) outer = v();
        if (outer.hasNext()) {
          var val = outer.next();
          inner = val();
          res.hasNext = innerF;
          return innerF();
        } else {
          return false;
        }
      }
      innerF = function () {
        if (inner.hasNext()) {
          return true;
        } else {
          return outerF();
        }
      }
      
      res.hasNext = outerF;
      return res;
    }
    
  }
}

